#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :article.py
# @Time      :2025/2/18 10:48
# @Author    :kk
import json

from flask import Blueprint,request, render_template, redirect, url_for

from models import Article

# /auth
bp = Blueprint("article",__name__,url_prefix="/article")

# 其他配置和路由
@bp.route('/')
def index():
    articles = Article.objects()
    return render_template('article/article_list.html', articles=articles)

@bp.route('/article/<id>')
def article(id):

    article = Article.objects.get(id=id)
    return render_template('article/article_detail.html', article=article)

@bp.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == 'POST':
        title = request.form['title']
        author = request.form['author']
        content = request.form['content']
        new_article = Article(title=title, author=author, content=content)
        new_article.save()
        return redirect(url_for('article.index'))
    return render_template('article/create_article.html')

@bp.route('/edit/<id>', methods=['GET', 'POST'])
def edit(id):
    article = Article.objects.get(id=id)
    if request.method == 'POST':
        article.title = request.form['title']
        article.author = request.form['author']
        article.content = request.form['content']
        article.save()
        return redirect(url_for('article.article', id=article.id))
    return render_template('article/edit_article.html', article=article)

@bp.route('/delete/<id>', methods=['POST'])
def delete(id):
    article = Article.objects.get(id=id)
    article.delete()
    return redirect(url_for('article.index'))


